# -*- coding: utf-8 -*-
import torch
import os
from torch import nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt

use_gpu = torch.cuda.is_available()
EPOCH = 1
BATCH_SIZE = 32
TIME_STEP = 28
INPUT_SIZE = 28
LR = 0.01
DOWNLOAD_MNIST = True
# mnist手写数字
train_data = dsets.MNIST(
    root='./mnist/',
    train=True,
    transform = transforms.ToTensor(),
    download=DOWNLOAD_MNIST,
)
'''
plt.imshow(train_data.train_data[11].numpy(), cmap='gray')
plt.title('%i' % train_data.train_labels[11])
plt.show()
'''
# 批量训练
train_loader = torch.utils.data.DataLoader(dataset = train_data, batch_size = BATCH_SIZE, shuffle = True)
# 测试
test_data = dsets.MNIST(root='./mnist/', train=False, transform = transforms.ToTensor())
test_x = test_data.test_data.type(torch.FloatTensor)[:2000]/255
test_y = test_data.test_labels.numpy().squeeze()[:2000]
# 建立神经网络
class RNN(nn.Module):
    def __init__(self):
        super(RNN, self).__init__()
        self.nn = nn.LSTM(
            input_size=INPUT_SIZE,
            hidden_size=64,
            num_layers=1,
            batch_first=True,
        )
        self.out = nn.Linear(64,10)  #输出层
    def forward(self, x):
        r_out, (h_n, h_c) = self.nn(x, None)
        out = self.out(r_out[:, -1, :])
        return out

rnn = RNN()
# if use_gpu:
#     rnn.cuda()
# 优化
optimizer = torch.optim.Adam(rnn.parameters(), lr=LR)
loss_func = nn.CrossEntropyLoss()            #损失函数

for epoch in range(EPOCH):
    for step, (b_x, b_y) in enumerate(train_loader):   #给出批处理数据
        b_x = b_x.view(-1,28,28)
        output = rnn(b_x)
        loss = loss_func(output, b_y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        if step % 50 == 0:
            test_output = rnn(test_x)
            pred_y = torch.max(test_output, 1)[1].data.numpy().squeeze()
            accuracy = float((pred_y == test_y).astype(int).sum()) / float(test_y.size)
            print('train loss:%.4f',loss.data.numpy(),'-+-+-+-test accuracy:%.2f',accuracy)

    test_output = rnn(test_x[:10].view(-1,28,28))
    pred_y = torch.max(test_output, 1)[1].data.numpy().squeeze()
    print(pred_y, 'prediction number')
    print(test_y[:10], 'real number')